<template>
  <view class="container">
    <!-- 直连的不展示 -->
    <view class="tips" v-if="directConnectChannel == false">
      <view>同步OTA渠道数据需要一定时间，如果账号密码错误会在列表内提示</view>
    </view>
    <view class="order-sync-form">
      <ve-form ref="formRef" :model="form" :rules="rules">
        <ve-card>
          <ve-form-item label="渠道名称" required prop="sourceId">
            <!-- 铁行二期不可修改 -->
            <ve-picker-inline disabled v-model="form.sourceId" placeholder="请选择" :range="dict.thirdpartySourceEnum" unit="arrowRight" />
          </ve-form-item>
          <!-- 直连的不展示 -->
          <ve-form-item v-if="directConnectChannel == false" label="渠道账户" required prop="username">
            <ve-input v-model="form.username" placeholder="请输入" :maxlength="30" />
          </ve-form-item>
          <!-- 直连的不展示 -->
          <ve-form-item v-if="directConnectChannel == false" label="渠道密码" required prop="password">
            <ve-input v-model="form.password" placeholder="请输入" :maxlength="20" />
          </ve-form-item>
          <ve-form-item label="运营主体" required prop="subject">
            <ve-input v-model="form.subject" placeholder="请输入" :maxlength="20" />
          </ve-form-item>
          <ve-form-item
            v-if="form.sourceId === 2"
            label="悟空加盟商ID"
            required
            prop="groupId"
            labelTooltipContent="悟空平台JM开头ID"
            labelTooltipPosition="top"
          >
            <ve-input v-model="form.groupId" placeholder="请输入" :maxlength="30" />
          </ve-form-item>
          <ve-form-item label="平台抽佣比" prop="commissionRate" labelTooltipPosition="top" :borderBottom="false" unit="%">
            <template #content>
              <view style="margin-bottom: 12rpx">输入抽佣比例，根据平台实际订单金额</view>
              <view>（去除平台承担优惠）计算平台佣金</view>
            </template>
            <ve-input-number :min="0" :max="100" :precision="2" v-model="form.commissionRate" placeholder="请输入" />
          </ve-form-item>
        </ve-card>
      </ve-form>

      <!-- 开通中状态、 铁行、飞租 直连展示对接步骤（渠道不可修改） -->
      <view v-if="directConnectChannel && accountInfo.status == 3" class="account-info-desc">
        <view class="desc-item" v-for="item in stepList" :key="item.step">
          <view class="desc-item-label">
            <view class="circle">{{ item.step }}</view>
            <view class="step-text">{{ item.text }}</view>
          </view>
          <view class="desc-item-value">
            <template v-for="content in item.content" :key="content.value">
              <span :style="{ color: content.color }">{{ content.value }}</span>
            </template>

            <view class="desc-item-imgList" v-if="item?.imgList?.length > 0">
              <template v-for="img in item.imgList" :key="img.value">
                <view class="desc-item-img">
                  <image :style="{ width: img.width + 'px' }" :src="img.img" mode="widthFix" @click="onPreviewImg(img.img)" />
                  <span class="text-xs">{{ img.value }}</span>
                </view>
              </template>
            </view>

            <view class="custom-name-list" v-if="item?.nameList?.length > 0">
              <template v-for="name in item.nameList" :key="name.value">
                <view :style="{ color: name.color, fontWeight: 600 }">{{ name.value }}</view>
                <template v-for="child in name.children" :key="child.value">
                  <view :style="{ width: '55%', color: child.color, textDecoration: 'underline' }" @click="onCallPhone(child.value)">
                    {{ child.value }}
                  </view>
                </template>
              </template>
            </view>
          </view>
        </view>
      </view>
    </view>

    <ve-bottom-box size="mini">
      <ve-button type="primary" :loading="loading" size="long" @click="onSubmit">确定</ve-button>
    </ve-bottom-box>

    <!-- 悟空渠道账号变更弹窗 -->
    <ve-modal title="提示" v-model="wukongAccountModalValue" :showCancel="false" @confirm="onWukongModalConfirm">
      <view style="padding-bottom: 24rpx; text-align: center">渠道账号变更，请进行验证</view>
    </ve-modal>

    <ve-modal title="短信验证码" v-model="smsCodeModalValue">
      <ve-form ref="smsCodeModalFormRef" :model="smsCodeModalForm" :rules="smsCodeModalRules">
        <ve-form-item valuePosition="left">
          <view>
            验证码已发送至手机号：
            <template v-if="form.sourceId === 5">
              {{ feizhuPhone }}
            </template>
            <template v-else>
              {{ form.username }}
            </template>
          </view>
        </ve-form-item>
        <ve-form-item label="验证码" required prop="smsCode" :borderBottom="false">
          <ve-input v-model="smsCodeModalForm.smsCode" placeholder="请输入" :maxlength="20" />
          <ve-button v-if="form.sourceId !== 5" class="smscode-button" type="link" size="mini" :disabled="disabled" @click="onModalSmsCode">
            {{ btnText }}
          </ve-button>
        </ve-form-item>
      </ve-form>
      <template #footer>
        <ve-button type="link" size="long" @click="onSmsCodeModalCancel" class="smsText">取消</ve-button>
        <view class="divider"></view>
        <ve-button type="link" :loading="smsModalLoading" size="long" class="smsText blue" @click="onSmsCodeModalConfirm">确定</ve-button>
      </template>
    </ve-modal>

    <!-- 飞猪排队弹窗 -->
    <ve-modal
      title="账号校验"
      v-model="feizhuTaskModalValue"
      :showConfirm="false"
      cancelText="不想等了，稍后在尝试"
      @cancel="onFeizhuTaskModalCancel"
    >
      <view class="feizhu-task-box">
        <view class="task-item">当前有其他进行中的校验任务，请您稍作等待</view>
        <view class="task-item" style="color: rgba(245, 63, 63, 1)">等待期间，请不要关闭此弹窗</view>
      </view>
    </ve-modal>
  </view>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from 'vue'
  import { onLoad, onShow } from '@dcloudio/uni-app'
  import { getDetailAPI, editAccountAPI, checkAccountAPI, checkAccountCodeAPI, checkAccountStopAPI } from '@/api/order/sOrder'
  import { usePageDict } from '@/hooks/useDict'
  import useCountLoop from '../hooks/useCountLoop'
  import { clearFeizhuTimer, feizhuDetailLoop, closeDialog } from '../utils'

  const { doLoop, clearLoop, btnText, disabled } = useCountLoop()
  const { startTimer, clearTimer } = closeDialog()

  const dict = ref()

  // 直连渠道 铁行、飞租
  const directConnectChannel = computed(() => {
    return form.value.sourceId && (form.value.sourceId == 7 || form.value.sourceId == 8)
  })
  const stepList = computed(() => {
    if (form.value.sourceId == 7) {
      return [
        {
          step: 1,
          text: '第一步',
          content: [
            {
              color: '#1D2129',
              value: '如果未在铁行平台进行过注册，请先扫描下方二维码前往铁行完成商户的注册。',
            },
          ],
          imgList: [
            {
              img: '/static/images/txalipay.png',
              width: 110,
              value: '打开支付宝扫一扫',
            },
            {
              img: '/static/images/txwechat.png',
              width: 110,
              value: '打开微信扫一扫',
            },
          ],
          nameList: [
            {
              color: '#1D2129',
              value: '铁行渠道平台商务对接人',
              children: [
                {
                  color: '#3072F6',
                  value: '房经理：15675537830',
                },
                {
                  color: '#3072F6',
                  value: '管经理：025-52393218',
                },
              ],
            },
          ],
        },
        {
          step: 2,
          text: '第二步',
          content: [
            {
              color: '#1D2129',
              value: '完成铁行平台的商户注册，并且在企橙平台创建铁行渠道账号后，账号会暂时处于【开通中】的状态；',
            },
          ],
        },
        {
          step: 3,
          text: '第三步',
          content: [
            {
              color: '#1D2129',
              value: '此时请联系企橙工作人员，开通铁行的对接服务；',
            },
          ],
        },
        {
          step: 4,
          text: '第四步',
          content: [
            {
              color: '#1D2129',
              value: '成功开通铁行渠道对接后，账号状态变为【开启】，即可进行铁行订单和库存的同步。',
            },
          ],
        },
      ]
    }
    return [
      {
        step: 1,
        text: '第一步',
        content: [
          {
            color: '#1D2129',
            value: '如果未在飞租平台进行过注册，请先联系飞租完成商户的注册。',
          },
        ],
        nameList: [
          {
            color: '#1D2129',
            value: '飞租渠道平台商务对接人',
            children: [
              {
                color: '#3072F6',
                value: '曲殿成：15201078711',
              },
              {
                color: '#3072F6',
                value: '曹静杰：17343040043',
              },
            ],
          },
        ],
      },
      {
        step: 2,
        text: '第二步',
        content: [
          {
            color: '#1D2129',
            value: '完成飞租平台的商户注册，并且在企橙平台创建飞租渠道账号后，账号会暂时处于【开通中】的状态；',
          },
        ],
      },
      {
        step: 3,
        text: '第三步',
        content: [
          {
            color: '#1D2129',
            value: '此时请联系企橙工作人员，开通飞租的对接服务；',
          },
        ],
      },
      {
        step: 4,
        text: '第四步',
        content: [
          {
            color: '#1D2129',
            value: '成功开通飞租渠道对接后，账号状态变为【开启】，即可进行飞租订单和库存的同步。',
          },
        ],
      },
    ]
  })

  const syncId = ref() // 订单ID
  const feizhuTaskModalValue = ref(false)
  const wukongAccountModalValue = ref(false)
  const smsCodeModalValue = ref(false)
  const smsCodeModalFormRef = ref()
  const formRef = ref()
  const form = ref<any>({})
  const smsCodeModalForm = ref<any>({})
  // 正则表达式，仅支持英文、数字、符号
  const reg = /^[\x21-\x7E]+$/
  const rules = ref<any>({
    sourceId: {
      required: true,
      message: '请选择',
    },
    // username: {
    //   required: true,
    //   message: '请输入',
    // },
    // password: {
    //   required: true,
    //   validator: (rule: any, value: any, callback: any) => {
    //     console.log(rule, value, callback, 'validator')
    //     if (value && reg.test(value)) {
    //       callback()
    //     } else {
    //       callback('渠道密码仅支持数字、字母、符号')
    //     }
    //   },
    // },
    subject: {
      required: true,
      message: '请输入',
    },
    // groupId: {
    //   required: true,
    //   validator: (rule: any, value: any, callback: any) => {
    //     console.log('groupId, validator', rule, value, callback, reg.test(value))
    //     if (value && reg.test(value)) {
    //       callback()
    //     } else {
    //       callback('悟空加盟商ID仅支持数字、字母、符号')
    //     }
    //   },
    // },
  })
  const smsCodeModalRules = ref({
    smsCode: {
      required: true,
      message: '请输入',
    },
  })
  const remoteSelectData = {
    prop: 'sourceName',
    label: '',
    type: 'remote-select',
    attr: {
      type: 'sourceName',
    },
  }

  // 不想等了，稍后在尝试
  const onFeizhuTaskModalCancel = () => {
    loading.value = false
    checkAccountStopAPI({ msgId: feizhuTaskId.value, id: syncId.value }).then((res: any) => {
      console.log(res, 'onFeizhuTaskModalCancel')
      feizhuTaskModalValue.value = false
      clearFeizhuTimer()
    })
  }

  const onWukongModalConfirm = () => {
    wukongAccountModalValue.value = false
    smsCodeModalValue.value = true
    startTimer(5 * 60 * 1000).then(() => {
      onSmsCodeModalCancel(false)
    })
  }

  const onSmsCodeModalCancel = (back = true) => {
    loading.value = false
    smsCodeModalValue.value = false
    smsModalLoading.value = false
    smsCodeModalForm.value = {}
    btnText.value = '获取验证码'
    clearLoop()
    clearTimer()

    checkAccountStopAPI({ msgId: feizhuTaskId.value, id: syncId.value }).then((res: any) => {
      console.log(res, 'onSmsCodeModalCancel')
    })
    if (back) {
      uni.navigateBack()
    }
  }

  // 获取验证码
  const onModalSmsCode = () => {
    const isLoop = doLoop()

    if (isLoop) {
      return
    }

    checkAccount()
  }

  const feizhuTaskId = ref() // 飞猪终止队列id
  // 账号验证
  const checkAccount = () => {
    return new Promise((resolve, reject) => {
      checkAccountAPI({ id: syncId.value })
        .then((res: any) => {
          console.log(res, 'checkAccountAPI')
          // 飞猪平台会返回终止队列id
          if (res.result) {
            feizhuTaskId.value = res.result
          } else {
            uni.showToast({
              title: '验证码发送成功',
              icon: 'none',
            })
          }
          resolve(res)
        })
        .catch((err: any) => {
          uni.showToast({
            title: err.message,
          })
          reject(err)
        })
    })
  }

  const smsModalLoading = ref(false)
  // 验证码弹窗确认
  const onSmsCodeModalConfirm = () => {
    smsModalLoading.value = true
    smsCodeModalFormRef.value.validate(async (valid: any, error: any) => {
      console.log(valid, error, 'onSmsCodeModalConfirm')

      if (valid) {
        try {
          // 填写验证码接口
          const result = await checkAccountCodeAPI({ id: syncId.value, smsCode: smsCodeModalForm.value.smsCode })
          console.log(result, 'onSmsCodeModalConfirm')

          if (form.value.sourceId === 5) {
            feizhuDetailLoop(
              (response: any) => {
                if (response.closeMsg) {
                  uni.showToast({
                    title: response.closeMsg,
                    icon: 'none',
                  })
                  smsModalLoading.value = false
                } else if (response.verifyFlag === 1) {
                  loading.value = false
                  smsCodeModalValue.value = false
                  smsModalLoading.value = false
                  smsCodeModalForm.value = {}
                  uni.navigateBack()
                } else if (response.verifyType === 1) {
                  // 需要验证
                  if (response.errMsg) {
                    uni.showToast({
                      title: response.errMsg,
                      icon: 'none',
                    })
                    smsModalLoading.value = false
                  } else {
                    response.loop()
                  }
                } else {
                  loading.value = false
                  smsCodeModalValue.value = false
                  smsModalLoading.value = false
                  smsCodeModalForm.value = {}
                  uni.navigateBack()
                }
              },
              (error: any) => {
                uni.showToast({
                  title: error.message,
                  icon: 'none',
                })
                smsModalLoading.value = false
              },
              getDetailFn,
            )
          } else {
            loading.value = false
            smsCodeModalValue.value = false
            smsModalLoading.value = false
            smsCodeModalForm.value = {}
            uni.navigateBack()
          }
        } catch (error: any) {
          console.log(error, 'onSmsCodeModalConfirm')

          uni.showToast({
            title: error.data.message,
            icon: 'none',
          })
          smsModalLoading.value = false
        }
      } else {
        smsModalLoading.value = false
      }
    })
  }

  const feizhuPhone = ref('')
  // 详情接口函数
  const getDetailFn = async () => {
    const { result } = await getDetailAPI({ id: syncId.value })
    const { extraDataJson } = result
    const { verifyPhone } = extraDataJson
    feizhuPhone.value = verifyPhone
    return result
  }

  /**
   * 2 悟空
   * 3 哈啰
   * 4 携程
   * 5 飞猪
   */
  const loading = ref(false)
  const onSubmit = () => {
    loading.value = true
    formRef.value.validate((valid: any) => {
      if (valid) {
        // 编辑账号信息接口
        editAccountAPI(form.value)
          .then((res: any) => {
            console.log(res, 'editAccountAPI')
            const { sourceId, verifyFlag } = res.result
            if (verifyFlag === 0) {
              // 悟空平台
              if (sourceId === 2) {
                wukongAccountModalValue.value = true
              } else if (sourceId === 5) {
                // 弹出飞猪队列等待弹窗
                feizhuTaskModalValue.value = true
                // 自动调用短信验证码接口
                checkAccount()
                  .then(() => {
                    feizhuDetailLoop(
                      (response: any) => {
                        feizhuTaskModalValue.value = false
                        if (response.closeMsg) {
                          uni.showToast({
                            title: response.closeMsg,
                            icon: 'none',
                          })
                          loading.value = false
                        } else if (response.verifyFlag === 1) {
                          // 不需要验证则关闭排队弹窗，直接返回，清除定时器
                          uni.navigateBack()
                          loading.value = false
                        } else if (response.verifyType === 1) {
                          if (response.errMsg) {
                            uni.showToast({
                              title: response.errMsg,
                              icon: 'none',
                            })
                            loading.value = false
                          } else {
                            smsCodeModalValue.value = true
                            startTimer(5 * 60 * 1000).then(() => {
                              onSmsCodeModalCancel(false)
                            })
                          }
                        } else {
                          uni.navigateBack()
                          loading.value = false
                        }
                      },
                      (error: any) => {
                        loading.value = false
                        feizhuTaskModalValue.value = false
                        uni.showToast({
                          title: error.message,
                          icon: 'none',
                        })
                      },
                      getDetailFn,
                    )
                  })
                  .catch((err: any) => {
                    loading.value = false
                    feizhuTaskModalValue.value = false
                    uni.showToast({
                      title: err.message,
                      icon: 'none',
                    })
                  })
              }
            } else {
              uni.navigateBack()
              loading.value = false
            }
          })
          .catch((err: any) => {
            uni.showToast({
              title: err.data.message,
              icon: 'none',
            })
            loading.value = false
          })
      } else {
        loading.value = false
      }
    })
  }

  const onPreviewImg = (url: string) => {
    uni.previewImage({
      current: url,
      urls: [url],
    })
  }

  const onCallPhone = (value: string) => {
    const phone = value.replace(/[^\d]/g, '')

    uni.makePhoneCall({
      phoneNumber: phone,
    })
  }

  const accountInfo = ref()
  onLoad((option: any) => {
    if (option.id) {
      syncId.value = option.id
      getDetailAPI({ id: option.id }).then((res: any) => {
        const result = res.result
        Object.assign(form.value, result)
        accountInfo.value = result
        remoteSelectData.label = result.sourceName
      })
    }
  })

  watch(
    () => form.value.sourceId,
    (newVal: any) => {
      console.log('form.value.sourceId', newVal)
      // form-item 初始化显示出来后，form组件内已经拿到children的prop值，rules不再变化
      // 即便sourceId变化，也不会重新执行rules，所以要根据sourceId变化，手动设置rules
      if (newVal != 7) {
        rules.value.username = {
          required: true,
          message: '请输入',
        }
        rules.value.password = {
          required: true,
          validator: (rule: any, value: any, callback: any) => {
            console.log('password validator', rule, value, callback)
            if (reg.test(value)) {
              callback()
            } else {
              callback('渠道密码仅支持数字、字母、符号')
            }
          },
        }
      } else {
        rules.value.username = {}
        rules.value.password = {}
      }

      if (newVal == 2) {
        rules.value.groupId = {
          required: true,
          validator: (rule: any, value: any, callback: any) => {
            console.log('groupId, validator', rule, value, callback, reg.test(value))
            if (value && reg.test(value)) {
              callback()
            } else {
              callback('悟空加盟商ID仅支持数字、字母、符号')
            }
          },
        }
      } else {
        rules.value.groupId = {}
      }
    },
  )

  onShow(() => {
    dict.value = usePageDict('syncChannelDicr', undefined, false)
    console.log(dict, 'dict')
  })
</script>

<style lang="less" scoped>
  .account-info-desc {
    background-color: #e8f3ff;
    padding: 23px 20px;
    font-weight: 400;
    font-size: 14px;

    .desc-item {
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .desc-item-label {
        display: flex;
        align-items: center;
        font-weight: 600;
        color: #165dff;

        .circle {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 16px;
          height: 16px;
          background-color: #165dff;
          color: #fff;
          border-radius: 50%;
          margin-right: 8px;
        }
      }

      .desc-item-value {
        padding-left: 24px;

        .desc-item-imgList {
          display: flex;
          gap: 20px;
          margin-top: 8px;
          margin-bottom: 8px;

          .desc-item-img {
            display: flex;
            flex-direction: column;
            align-items: center;

            .text-xs {
              font-size: 12px;
              color: #1d2129;
              margin-top: 8px;
            }
          }
        }

        .custom-name-list {
          view {
            margin-bottom: 8px;
          }
        }
      }
    }
  }

  .divider {
    width: 2rpx;
    height: 100%;
    background: #e8e8e8;
  }
  .smsText {
    height: 100%;
    font-size: 16px;
    font-weight: 400;
    color: #191c27;

    &.blue {
      color: rgba(48, 114, 246, 1);
    }
  }
  .feizhu-task-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-bottom: 24rpx;
  }
  .tips {
    width: 100%;
    background: #e8f3ff;
    padding: 18rpx 32rpx;
    color: #1d2129;
    font-size: 24rpx;
    font-weight: 400;
  }
  .order-sync-form {
    padding: 24rpx 24rpx;
  }

  .smscode-button {
    width: 180px;
  }
</style>
